package com.sqtracker.recommender.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.data.mongodb.core.MongoTemplate;

import javax.annotation.PreDestroy;

/**
 * 嵌入式MongoDB测试配置
 * 使用spring-boot提供的自动配置
 */
@TestConfiguration
@Profile("test")
public class EmbeddedMongoConfig {

    @Value("${spring.data.mongodb.uri:mongodb://localhost:27017}")
    private String connectionString;

    @Value("${spring.data.mongodb.database:test}")
    private String databaseName;

    private MongoClient mongoClient;

    @Bean
    @Primary
    public MongoClient mongoClient() {
        if (mongoClient == null) {
            mongoClient = MongoClients.create(connectionString);
        }
        return mongoClient;
    }

    @Bean
    @Primary
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoClient(), databaseName);
    }

    @PreDestroy
    public void cleanup() {
        if (mongoClient != null) {
            mongoClient.close();
        }
    }
} 